package com.example.test

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.*
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.hjq.permissions.OnPermission
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import kotlinx.android.synthetic.main.activity_scrolling.*
import java.util.*

class GalleryActivity : AppCompatActivity() {

    private lateinit var allGalleryPhotos: MutableList<String>
    private lateinit var galleryItemAdapter: GalleryItemAdapter
    private lateinit var handler: Handler

    @RequiresApi(Build.VERSION_CODES.R)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scrolling)

        allGalleryPhotos = mutableListOf()
        galleryItemAdapter = GalleryItemAdapter(
            this@GalleryActivity,
            filePaths = allGalleryPhotos
        )
        gallery.adapter = galleryItemAdapter
        gallery.setOnItemClickListener { parent, view, position, id ->
            with(Intent(this,ShowActivity::class.java)){
                putExtra(IntentParamNames.FILE_PATH.name,allGalleryPhotos[position])
                startActivity(this)
            }
        }

        handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                galleryItemAdapter.notifyDataSetChanged()
            }
        }
        checkPermissionAndRefreshData()
    }

    private fun checkPermissionAndRefreshData() {
        XXPermissions.with(this)
            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
            .request(object : OnPermission {
                @RequiresApi(Build.VERSION_CODES.R)
                override fun hasPermission(granted: MutableList<String>?, all: Boolean) {
                    if (all) {
                        val loadPhotos = getAllGalleryPhotos(context = this@GalleryActivity)
                        loadPhotos?.let {
                            allGalleryPhotos.clear()
                            allGalleryPhotos.addAll(loadPhotos)
                            handler.sendEmptyMessage(RESULT_OK)
                        }
                    }
                }

                override fun noPermission(denied: MutableList<String>?, never: Boolean) {
                    if (never) {
                        Toast.makeText(this@GalleryActivity, "无法获取存储权限! ", Toast.LENGTH_SHORT)
                            .show()
                        setResult(RESULT_CANCELED)
                        finish()
                    }
                }

            })
    }

    override fun onResume() {
        Log.i("dev", "onResume: ")
        super.onResume()
        checkPermissionAndRefreshData()
    }

    @SuppressLint("Recycle")
    @RequiresApi(Build.VERSION_CODES.R)
    private fun getAllGalleryPhotos(context: Context): List<String>? {
        val images = arrayListOf<String>()
        val album = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val cursor = context.contentResolver.query(album, null, null, null)
        if (cursor == null || cursor.count <= 0) {
            return null
        }
        while (cursor.moveToNext()) {
            val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
            val filePath = cursor.getString(columnIndex)
            images.add(filePath)
        }
        return images
    }


    class GalleryItemAdapter(private val context: Context, val filePaths: List<String>?) :
        BaseAdapter() {

        override fun getCount(): Int {
            if (filePaths != null) {
                return filePaths.size
            }
            return 0
        }

        override fun getItem(position: Int): String? {
            return filePaths?.get(position)
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            // 加载图片
            val imageView: ImageView = if (convertView == null) {
                LayoutInflater.from(context).inflate(R.layout.item, parent, false) as ImageView
            } else {
                convertView as ImageView
            }
            val options = BitmapFactory.Options()
            options.inSampleSize = 4
            val decodeFile = BitmapFactory.decodeFile(filePaths?.get(position),options)
            // 压缩图片
//            decodeFile.compress()
            imageView.setImageBitmap(decodeFile)
            return imageView
        }

    }

}